import { defineStore } from 'pinia'
import { resetAllStorages, resetAllStores, useProfileStore, useWalletStore } from '@/store'
import {
	login,
	loginVerifyCode,
	logout,
	register,
	thirdPartyInfo,
	thirdPartyRegister
} from '@/api/account'
import { AccountShowType } from '@/types'
import {
	FacebookAuthProvider,
	getAuth,
	GoogleAuthProvider,
	signInWithPopup,
	signOut
} from 'firebase/auth'
import { removeItem, setItem, showError, showSuccess, t } from '@/utils'
import firebase from '@/utils/firebase'
import { THIRD_PLATFORM_LIST } from '@/constants'
import {
	Login,
	LoginVerify,
	ThirdCallbackParams,
	ThirdPartyInfo,
	ThirdPartyRegister
} from '@/api/account-type.ts'
import router from '@/router'
import { useAppStore } from '@/store'

const auth = getAuth(firebase)
const googleProvider = new GoogleAuthProvider()
const FacebookProvider = new FacebookAuthProvider()

export const useAccountStore = defineStore('account', {
	state: () => ({
		loginParams: null as Login['params'] | null,
		loginResult: null as Login['result'] | null,
		resetResult: null as Login['result'] | null,
		token: '',
		thirdToken: '',
		thirdCallbackLink: '',
		thirdCallbackParams: null as ThirdCallbackParams | null,
		thirdPartyInfo: null as ThirdPartyInfo['result'] | null,
		resetToken: '',
		accountShow: AccountShowType.none as AccountShowType
	}),
	actions: {
		setLoginParams(data: Login['params']) {
			this.loginParams = data
		},
		setLoginResult(data: Login['result']) {
			this.loginResult = data
		},
		setResetResult(data: any) {
			this.resetResult = data
		},
		setToken(val: string) {
			this.token = val
		},
		setThirdToken(val: string) {
			this.thirdToken = val
		},
		showAccount(type: AccountShowType) {
			this.accountShow = type
			switch (type) {
				case AccountShowType.login:
					return router.replace({ query: { tab: 'login', modal: 'auth' } })
				case AccountShowType.register:
					return router.replace({ query: { tab: 'register', modal: 'auth' } })
				case AccountShowType.forgotPassword:
					return router.replace({ query: { tab: 'forgot-password', modal: 'auth' } })
				case AccountShowType.none:
					return router.replace({ query: {} })
			}
		},
		showLogin() {
			this.accountShow = AccountShowType.login
		},
		showRegister() {
			this.accountShow = AccountShowType.register
		},
		showThirdRegister() {
			this.accountShow = AccountShowType.thirdRegister
		},
		showReset(resetToken: string) {
			this.accountShow = AccountShowType.resetPassword
			this.resetToken = resetToken
		},
		clearLoginInfo() {
			const profileStore = useProfileStore()
			this.setToken('')
			this.logoutThird().then()
			profileStore.clearUserInfo().then()
			resetAllStores()
			resetAllStorages()
			//router.replace('/')
		},
		async getAccountInfo() {
			const profileStore = useProfileStore()
			// const appStore = useAppStore()
			const walletStore = useWalletStore()
			await Promise.all([
				profileStore.getUserInfo(),
				walletStore.getUserWalletConfig(),
				walletStore.getWalletConfigList()
				// appStore.getNoticeUnread(),
				// walletStore.getChannelInfo(),
				// walletStore.getWithdrawChannel()
			])
			//router.replace('/')
		},
		async login(val: Login['params']) {
			this.setLoginParams(val)
			const { data } = await login(val)
			this.setLoginResult(data)
			if (data.accessToken) {
				this.setToken(data.accessToken)
				await this.getAccountInfo()
				this.showAccount(AccountShowType.none)
			} else {
				this.showAccount(AccountShowType.loginVerify)
			}
			return data
		},
		async loginVerifyCode(val: LoginVerify['params']) {
			const { data } = await loginVerifyCode(val)
			this.setToken(data.accessToken)
			await this.getAccountInfo()
		},
		async register(val: any) {
			const { data } = await register(val)
			this.setToken(data.accessToken)
			await this.getAccountInfo()
		},
		// async reset(val: any) {
		// 	const { data } = await resetPassword(val)
		// 	this.setToken(data.accessToken)
		// 	await this.getAccountInfo()
		// },
		async logout() {
			await logout()
			const appStore = useAppStore()
			router.push({ name: 'home', params: { locale: appStore.lang } })
			this.clearLoginInfo()
		},
		async thirdSignIn(data: any) {
			this.setToken(data.accessToken)
			await this.getAccountInfo()
		},
		async thirdLogin() {
			try {
				if (this.thirdCallbackParams) {
					await this.thirdRegister({
						// userId: null,
						authId: this.thirdPartyInfo?.authId || null,
						source: this.thirdPartyInfo?.source || null,
						email: this.thirdPartyInfo?.email || null
						// username: null,
						// inviteCode: null
					})
				}
			} catch (e) {
				showError(e)
			}
		},
		async thirdRegister(params: ThirdPartyRegister['params']) {
			const { data } = await thirdPartyRegister(params)
			this.setToken(data.accessToken)
			await this.thirdSignIn(data)
			this.showAccount(AccountShowType.none)
			showSuccess(t('login.success'))
		},
		async thirdPartyCheck() {
			try {
				if (this.thirdCallbackParams) {
					const { data } = await thirdPartyInfo({ ...this.thirdCallbackParams })
					this.thirdPartyInfo = data
					if (data.register) {
						await this.thirdLogin()
					} else {
						this.showThirdRegister()
					}
				}
			} catch (e) {
				showError(e)
			}
		},
		async getThirdToken(key: string) {
			const provider = key === 'google' ? googleProvider : FacebookProvider
			provider.setCustomParameters({
				prompt: 'select_account'
			})
			const result = await signInWithPopup(auth, provider)
			//  TODO 这里需要储存一下 登录的平台
			console.log('3rd result', result)
			const idTokenResult = await result.user.getIdTokenResult()
			const token = idTokenResult.token
			this.setThirdToken(token)
			// 存入第三方token 方便绑定和解绑使用
			setItem((key + '_Token').toUpperCase(), token)
		},
		async logoutThird() {
			this.setToken('')
			THIRD_PLATFORM_LIST.forEach((key: string) => {
				removeItem(key.toUpperCase() + '_TOKEN')
			})
			await signOut(auth)
		}
	},
	getters: {
		isLogin: (state) => !!state.token
	},
	persist: true
})
